var prefix = jsctx + "/sys/content";

var content = (function () {
    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        },10)
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });
    var h = $(window).height() - 80;
    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageContent",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    cache: false,
                    pageSize: 20,
                    pageList: [10,20,30],
                    pageNumber: 1,
                    sidePagination: "server",
                    paginationShowPageGo: true,
                    height: h,
                    queryParams: function (params) {
                        return {
                            pageSize: params.limit,
                            pageNo: (params.offset / params.limit) + 1,
                            title: $("#title").val().trim()
                        };
                    },
                    columns: [
                        {
                            title: 'id', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'agreementTitle', title: '标题', width: '100', align: 'left'},
                        // {
                        //     field: 'noticeType', title: '公告类型',
                        //     width: '75', align: 'center',
                        //     formatter: function (value, row, index) {
                        //         if (value == '0') {
                        //             return '<span >系统</span>'
                        //         } else if (value == '1') {
                        //             return '<span >活动</span>'
                        //         }
                        //     }
                        // },
                        // {field: 'content', title: '内容', width: '200', align: 'center'},
                        // {
                        //     field: '', title: '标签',
                        //     width: '100', align: 'center',
                        //     formatter: function (value, row, index) {
                        //         if (row.noticeType == '1') {
                        //             return '';
                        //         } else if (row.noticeType == '0') {
                        //             if (row.informType == '0') {
                        //                 return '重要通知(蓝色)';
                        //             } else if (row.informType == '1') {
                        //                 return '节日公告(橙色)'
                        //             }else if (row.informType == '2') {
                        //                 return '日常通知(绿色)'
                        //             }else if (row.informType == '3') {
                        //                 return '系统升级(蓝色)'
                        //             }else if (row.informType == '4') {
                        //                 return '暂停服务(红色)'
                        //             }else if (row.informType == '5') {
                        //                 return '功能上线(橙色)'
                        //             }else if (row.informType == '5') {
                        //                 return '其他(紫色)'
                        //             }
                        //         }
                        //     }
                        // },
                        // {
                        //     field: '', title: '图片',
                        //     width: '100', align: 'center',
                        //     formatter: function (value, row, index) {
                        //         if (row.noticeType == '1') {
                        //             return '<img  src="' + row.imgUrl + '"width="155px" height="120px"/>';
                        //         } else if (row.noticeType == '0') {
                        //             return ''
                        //         }
                        //     }
                        // },
                        // {
                        //     field: '', title: '访问地址(URL)',
                        //     width: '200', align: 'center',
                        //     formatter: function (value, row, index) {
                        //         if (row.noticeType == '1') {
                        //             return row.accessUrl
                        //         } else if (row.noticeType == '0') {
                        //             return ''
                        //         }
                        //     }
                        // },
                        {field: 'createdTime', title: '创建时间', width: '100', align: 'left'},
                        // {field: 'publishTime', title: '发布时间', width: '100', align: 'left'},
                        // {
                        //     field: '', title: '接收对象',
                        //     width: '75', align: 'center',
                        //     formatter: function (value, row, index) {
                        //         if (row.memberType == '1') {
                        //             return '指定用户'
                        //         } else if (row.memberType == '0') {
                        //             return '全部用户'
                        //         }
                        //     }
                        // },
                        {
                            field: 'status', title: '状态', width: '75', align: 'center',
                            formatter: function (value, row, index) {

                                if (value == '0') {
                                    return  '<input class="tgl tgl-skewed" onclick="content.onSwitchChange(' + row.agreementNotificationId +',1 )" id="cb'+row.agreementNotificationId+'" type="checkbox"><label class="tgl-btn" data-tg-off="启动" data-tg-on="禁用" for="cb'+row.agreementNotificationId+'"></label>'
                                } else {
                                    return '<input class="tgl tgl-skeweds"  onclick="content.onSwitchChange(' + row.agreementNotificationId +',0 )" id="cb'+row.agreementNotificationId+'" type="checkbox"> <label class="tgl-btn isok" data-tg-off="禁用" data-tg-on="启动" for="cb'+row.agreementNotificationId+'"></label>'
                                }
                            }
                        },
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {


                                var a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" title="编辑" onclick="content.edit(\''
                                    + row.agreementNotificationId
                                    + '\')">编辑</a> ';

                                return a;

                            }
                        }
                    ],onLoadSuccess: function(){

                    },onPageChange: function() {

                    }
                });
    }

    function onSwitchChange (isId, state) {
        //修改操作
        $.ajax({
            type: "post",
            dataType: "json",
            async: false,
            url: prefix + "/udpateContentStatus",
            data: {
                status: state ,
                id: isId
            },
            success: function(data) {
                reLoad();
            },
            error: function(xhr, error, exception){
                let errorMsg = xhr.responseText;
                openMsg("error","系统异常，"+errorMsg+"，请联系管理员！");
            }
        });
    }


    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }

    function edit(id) {
        location.href = prefix + "/edit/" + id;
    }

    function add() {
        location.href = prefix + "/add";
    }


    function goBack() {
        window.history.back();
    }

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                title: $('#title').val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }


    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        edit: edit,
        onSwitchChange:onSwitchChange,
        exportList: exportList,
        add:add
    };
})();

var editContent = (function () {
    function init() {
        validateRule();
    };

    function getCheckedRoles() {
        var adIds = "";
        $("input:checkbox[name=role]:checked").each(function (i) {
            if (0 == i) {
                adIds = $(this).val();
            } else {
                adIds += ("," + $(this).val());
            }
        });
        return adIds;
    }

    var isajaxsend = true;

      function save() {
            var formData = new FormData($("#frmContent")[0]);
            $("#roleIds").val(getCheckedRoles());
            $.ajax({
                cache: true,
                type: "POST",
                url: prefix + "/saveContent",
                data: formData,
                processData: false,
                contentType: false,
                async: false,
                beforeSend: function () {
                    isajaxsend = false
                },
                error: function (request) {
                    parent.layer.alert("Connection error");
                },
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        window.history.back();
                    } else {
                        parent.layer.alert(data.message)
                    }

                },
                complete: function () {
                    isajaxsend = false
                }
            });
        }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmContent").validate({
            rules: {
                agreementTitle: {
                    required: true
                }

            },
            messages: {
                agreementTitle: {
                    required: icon + "请输入标题"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();
